package com.wiegand.gui.text.effects {

	/**
	 * @author wie-gand
	 */
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;

	public class TypingTextField extends TextField{

		private var _timer : Timer;
		private var _position : int = 0;			
		private var _delay : int = 25;
		private var _cursor : String = "_";	
		private var _showBlinkingCursor : Boolean = true;
		private var _showCursor : Boolean = true;		
		private var _text : String = "";
				
		public function TypingTextField() : void{
			
			super();
			
			_timer = new Timer( _delay );
			
			_timer.addEventListener( TimerEvent.TIMER, timerHandler );
			
		}
		
		public function get delay() : int{
			
			return _delay;
			
		}
		
		public function set delay( value : int ) : void{
			
			_delay = value;
			
		}

		public function get showBlinkingCursor() : Boolean{
			
			return _showBlinkingCursor;
			
		}
		
		public function set showBlinkingCursor( value : Boolean ) : void{
			
			_showBlinkingCursor = value;
			
		}

		public function get cursorText() : String{
			
			return _cursor;
		
		}
		
		public function set cursorText( value : String ) : void{
			
			_cursor = value;
		
		}

		override public function get text() : String{
			
			return _text;
		
		}
		
		override public function set text( value : String ) : void{
			
			if( _showBlinkingCursor && value.length > 0 ){
				
				super.text = _text;
			
			}
			else super.text = "";
					
			_text = value;
			
			if( value.length > 0 ){
				
				_timer.delay = _delay;
				
				_timer.start();
				
			}
		}
		
		private function timerHandler( e : TimerEvent ) : void{

			_timer.delay = _delay;
			
			_position++;
			
			if( _position > _text.length ){
				
				super.text = _text;
				
				_timer.stop();
				
				dispatchEvent( new Event( Event.COMPLETE ) );
				
				return;
			
			}
			
			_showCursor = !_showCursor;
			
			super.text = _text.substr( 0, _position ) + ( _showBlinkingCursor && _showCursor ? _cursor : "" );
		
		}
	
	}
	
}